﻿#include "connectThread.h"
#include "app.h"
#include <QtCore/QTime>
#include <QtSerialPort\QSerialPort>
#include <QtCore/qmath.h>
#include <windows.h>
#include <QtCore/QDebug>

ConnectThread::ConnectThread() :
	_portName(""),
	_baudrate(0) {
	stoped = false;
	txLength = 0;
	rxLength = 0;
	//解析数据
	broadcastDecode = new BroadcastDecode();
	circularArray = new CircularArray(broadcastDecode, 0x3F, 0x05, 0x02);
}

ConnectThread::~ConnectThread() {
	stoped = true;
	wait();
}

//线程停止函数
void ConnectThread::stop() {
	stoped = true;
}

//打开串口并线程启动
void ConnectThread::openPort(QString portName, qint32 baudrate) {
	_portName = portName;
	_baudrate = baudrate;
	if (!isRunning()) {
		start();
	}
}

//追加待发送内容
void ConnectThread::appendTx(QByteArray *src) {
	sendMutex.lock();
	sendData.append(*src);
	sendMutex.unlock();
}

//线程运行函数
void ConnectThread::run() {
	stoped = false;
	serialPort = new QSerialPort();
	//打开串口
	serialPort->setPortName(_portName);
	serialPort->setBaudRate(_baudrate);
	if (!serialPort->open(QIODevice::ReadWrite)) {
		emit error(QObject::tr("无法打开%1, 错误编号%2").arg(serialPort->portName()).arg(serialPort->error()));
		delete serialPort;
		serialPort = nullptr;
		return;
	}

	//先清除串口中的缓冲
	serialPort->clear();

	while (!stoped) {

		//发送用拷贝的数据减少上锁的时间
		sendMutex.lock();
		QByteArray txData = sendData;
		sendData.clear();
		sendMutex.unlock();
		if (txData.count() > 0) {
			serialPort->write(txData);
			txLength += txData.count();
			emit displayTxNum(txLength);

			//u8类型的数据显示及处理
			QString u8TxString;
			//转换为hex
			for (int i = 0; i < txData.count(); i++) {
				u8TxString += QString::asprintf("%02x ", (unsigned char)txData.at(i));
			}
			App::textMutex.lock();
			App::txStringList.append(u8TxString);
			App::textMutex.unlock();
		}
		if (serialPort->waitForReadyRead(10)) {
			//读取数据
			QByteArray rxData = serialPort->readAll();
			rxLength += rxData.count();
			emit displayRxNum(rxLength);

			//u8类型的数据显示及处理
			QString u8RxString;
			//转换为hex
			for (int i = 0; i < rxData.count(); i++) {
				u8RxString += QString::asprintf("%02x ", (unsigned char)rxData.at(i));
			}
			App::textMutex.lock();
			//传递前保证当前打开显示线程的情况下才对字符串进行追加
			App::rxStringList.append(u8RxString);
			App::textMutex.unlock();
			//原始字符串处理
			emit rawStringDecode(rxData);
			//将数据添加到回环数组
			circularArray->AddData(&rxData);
			//回环数组的数据解析
			circularArray->DecodeData();
		}
	}

	//退出线程时关闭串口
	serialPort->close();
	delete serialPort;
	serialPort = nullptr;
}

